//
//  DailyFeatureStoryViewController.m
//  GOGOTravel
//
//  Created by dllo on 16/1/28.
//  Copyright © 2016年 果果. All rights reserved.
//

#import "DailyFeatureStoryViewController.h"
#import "deLISTTableViewCell.h"
#import "TUWENTableViewCell.h"
#import "ShouChangViewController.h"
#import "UMSocial.h"
@interface DailyFeatureStoryViewController ()<UITableViewDataSource, UITableViewDelegate, TargetTableViewCellDelegate, UMSocialUIDelegate>

@property (nonatomic, retain) NSMutableArray *SpotArr;
@property (nonatomic, retain) UITableView *tableView; /**<  底层tableView */
@property (nonatomic, retain) NSMutableArray *tripArr;/**<  装trip的数组 */
@property (nonatomic, retain) NSMutableArray *deList;/**<  装图文的数组 */
@property (nonatomic, assign) CGRect rect;
@property (nonatomic, retain) NSMutableArray *recommendationArr;/**<  评论头像数组 */

@property (nonatomic, retain) UIBarButtonItem *item3;

@property (nonatomic, retain) NSString *urlString;/**<  关于收藏的网址 */

@property (nonatomic, assign) BOOL isFirstInsert;/**<  第一次插入数据库判断的变量 */
@property (nonatomic, assign) BOOL isDidInsert;/**<  已经插入数据库 */

@property (nonatomic, assign) BOOL isShouChang;/**<  已经收藏 */
@property (nonatomic, retain) UIBarButtonItem *item2;/**<  空心item */
@property (nonatomic, retain) UIBarButtonItem *itemShiXin;/**<  实心item */

@end

@implementation DailyFeatureStoryViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _isFirstInsert = YES;
        _isDidInsert = NO;
    }
    return self;
}
- (void)dealloc{
    [_SpotArr release];
    [_spotModel release];
    [_tableView release];
    [_tripArr release];
    [_deList release];
    [_recommendationArr release];
    [_item3 release];
    [_shouChangModel release];
    [_urlString release];
    [_url release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.translucent = NO;

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    self.navigationItem.title = @"故事详情";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNavigationItem];
    [self handleData];
    
    
}

/** 创建navigationItem */
- (void)initNavigationItem{
    
    //左箭头
    UIImage *image = [UIImage imageNamed:@"iconfont-jiantouzuo.png"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
    self.navigationItem.leftBarButtonItem = item;
    [item release];
    
    //空心心箭头
    UIImage *image2 = [UIImage imageNamed:@"iconfont-heilongjiangtubiao12.png"];
    UIBarButtonItem *item2= [[UIBarButtonItem alloc] initWithImage:image2 style:UIBarButtonItemStylePlain target:self action:@selector(item2Action:)];
    //分享
    UIImage *image3 = [UIImage imageNamed:@"iconfont-fenxiang.png"];
    self.item3 = [[UIBarButtonItem alloc] initWithImage:image3 style:UIBarButtonItemStylePlain target:self action:@selector(item3Action:)];
    
    //创建实心item
    UIBarButtonItem *itemShiXin = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-xinxing-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(itemShouC:)];
    
    
    
   
    NSArray *arr = [[DbHandel shareDbHandel] selectDailyTable];
    
    NSDictionary *dic = _model.data[0];
    
    if (arr.count < 1) {
         self.navigationItem.rightBarButtonItems = @[item2, _item3];
    }else{
        for (ShouChangModel *model in arr) {
            if ([model.titleLabelStr isEqualToString:dic[@"index_title"]]) {
                
                self.navigationItem.rightBarButtonItems = @[itemShiXin, _item3];
                
            }else{
                self.navigationItem.rightBarButtonItems = @[item2, _item3];
                
            }
        }
        
    }
    
    
    
    
    [itemShiXin release];
    [item2 release];
    [_item3 release];
}
/** item方法 */
- (void)itemAction:(UIBarButtonItem *)item{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)item2Action:(UIBarButtonItem *)item{

        NSArray *arrShouChang =[[DbHandel shareDbHandel] selectDailyTable];
        
        if (arrShouChang.count == 0) {
            
            [[DbHandel shareDbHandel] insertDailyModel:_shouChangModel];
            [self createAlert2];
            
            
            
            //创建实心item
            
            UIBarButtonItem *itemShiXin = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-xinxing-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(itemShouC:)];
            
            self.navigationItem.rightBarButtonItems = @[itemShiXin, _item3];
            
            
            
        }else{
        
            //取出model 中的cell 的标题
            NSDictionary *dic = _model.data[0];
            NSString *str = dic[@"index_title"];
            for (ShouChangModel *model in arrShouChang) {
                
                if ([model.titleLabelStr isEqualToString:str]) {
                    
                    [self createAlert];
                    
                }else{
                    if (_isDidInsert == NO) {
                        
                        [[DbHandel shareDbHandel] insertDailyModel:_shouChangModel];
                        [self createAlert2];
                        _isDidInsert = YES;
                        
                        //创建实心item
                        
                        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-xinxing-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(itemShouC:)];
                        
                        self.navigationItem.rightBarButtonItems = @[item, _item3];
                    }
                }
            }
            
        }
        
}

//实心item方法
- (void)itemShouC:(UIBarButtonItem *)item{
        [self createAlert];
}


- (void)createAlert{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"小主，你已经收藏过了" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}
- (void)createAlert2{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"小主，添加收藏成功" preferredStyle:UIAlertControllerStyleAlert];
    
    
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action];
    [alert addAction:action1];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];

}


- (void)item3Action:(UIBarButtonItem *)item{
    
        UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
        /**
         Sns平台类，用`platformName`作为标识，指定显示名称、显示的图片，点击之后的响应。
         */
        snsPlatform.displayName = @"新浪";
        
        
        UMSocialSnsPlatform *snsPlatform2 = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToTencent];
        snsPlatform2.displayName = @"腾讯微博";
        
        
        Spot *model = _SpotArr[0];
        
        NSString *str = model.text;
        if (str.length > 80) {
           
            NSNumber *spot = model.spot_id;
            NSString *result = [str substringToIndex:70];
            NSString *resultStr = [NSString stringWithFormat:@"#张洪国练出十块腹肌# %@...分享给大家~http://web.breadtrip.com/btrip/spot/%@/", result, spot];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56d6f3dee0f55a29fb0029fd"
                                              shareText:resultStr
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToWechatSession,nil]
                                               delegate:self];
            
            
        }else{
          
            NSNumber *spot = model.spot_id;
            NSString *result = str;
            NSString *resultStr = [NSString stringWithFormat:@"#张洪国练出十块腹肌# %@...分享给大家~http://web.breadtrip.com/btrip/spot/%@/", result, spot];
            
            
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56d6f3dee0f55a29fb0029fd"
                                              shareText:resultStr
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToWechatSession,nil]
                                               delegate:self];
            
            
        }
        
        
}

/** 创建uitableView */
- (void)initTableView{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //注册
    [_tableView registerNib:[UINib nibWithNibName:@"StoryAllTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"StoryAllTableViewCell"];
    //注册
    [_tableView registerClass:[deLISTTableViewCell class] forCellReuseIdentifier:@"deLISTTableViewCell"];
    //注册
    [_tableView registerClass:[TUWENTableViewCell class] forCellReuseIdentifier:@"TUWENTableViewCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"TWLastTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TWLastTableViewCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"TargetTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TargetTableViewCell"];
    
    [_tableView registerClass:[LikeTableViewCell class] forCellReuseIdentifier:@"LikeTableViewCell"];
    
    [_tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"BaseTableViewCell"];
    
}
/** 代理方法 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _deList.count + 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        Spot *spotModel = _SpotArr[0];
        Trip *tripModel = _tripArr[0];
        
        StoryAllTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StoryAllTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (spotModel.poi == nil) {
            cell.tripModel = tripModel;
            
        }else{
            cell.tripModel = tripModel;
            cell.spotModel = spotModel;
            
        }
        return cell;
    }else if (indexPath.row == 1 ){
        Spot *model = _SpotArr[0];
        deLISTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"deLISTTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = model;
       
        
        return cell;
    }else if (indexPath.row == _deList.count + 2){
        TWLastTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TWLastTableViewCell"];
        Trip *model = _tripArr[0];
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    
    }else if (indexPath.row == _deList.count + 3){
        
        TargetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TargetTableViewCell"];
        Spot *model = _SpotArr[0];
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.row == _deList.count + 4){
        //判断的话reload就不好使了
        if (_recommendationArr.count == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
            
            return cell;
        }else{
            Spot *model = _SpotArr[0];
            LikeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LikeTableViewCell"];
            cell.modelArr = _recommendationArr;
            cell.count = _recommendationArr.count;
            cell.model = model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    
    }else{
        TUWENTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TUWENTableViewCell"];
        deList *model = _deList[indexPath.row - 2];
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 100;
    }else if ( indexPath.row == 1){
        
        UITableViewCell *cell = [self tableView:_tableView cellForRowAtIndexPath:indexPath];
        
        return cell.frame.size.height;
    }else if (indexPath.row == _deList.count + 2){
        return 100;
    }else if (indexPath.row == _deList.count + 3){
        return 151;
    }else if(indexPath.row == _deList.count + 4){
        return 200;
    }else{
        UITableViewCell *cell = [self tableView:_tableView cellForRowAtIndexPath:indexPath];
        
        return cell.frame.size.height;
        
    }
    
}
/** 完成代理协议 */
- (void)JumpTOweb:(NSString *)str{
    ExperienceDetailsViewController *ex = [[ExperienceDetailsViewController alloc ] init];
    ex.url = str;
    [self.navigationController pushViewController:ex animated:YES];
    [ex release];

}





/** 数据处理 */
- (void)handleData{
    

    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=%@", _url];
    
  
    
    [AFNetWorkingHandle GETRequestWithURLString:url completionWithSuccess:^(id result) {
        
        NSDictionary *data = result[@"data"];
        NSDictionary *spot = data[@"spot"];
        NSDictionary *trip = data[@"trip"];
     
        self.SpotArr = [NSMutableArray array];
       
        self.tripArr = [NSMutableArray array];
        
        Spot *spotModel = [[Spot alloc] initWithDic:spot];
        
        //装图文的数组
        NSArray *arr = spotModel.detail_list;
        self.deList = [deList ModelHandleWithArray:arr];
        
      
        [_SpotArr addObject:spotModel];
       
       
        
        Trip *tripModel = [[Trip alloc] initWithDic:trip];
        [_tripArr addObject:tripModel];
        
        //评论头像数据处理
        NSArray *arrCom = spot[@"recommendations"];
        self.recommendationArr = [Recommendation ModelHandleWithArray:arrCom];
        
               [spotModel release];
        [tripModel release];
       [self initTableView];
        [_tableView reloadData];
    } withFailure:^(id error) {
        NSLog(@"%@", error);
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
